package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.NewsInfo;
import com.sywb.chuangyebao.bean.NewsOwner;
import com.sywb.chuangyebao.bean.QuestionInfo;
import com.sywb.chuangyebao.bean.SearchUser;
import com.sywb.chuangyebao.bean.SuperInfo;
import com.sywb.chuangyebao.bean.VideoData;
import com.sywb.chuangyebao.library.view.RatioImageView;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.RegexUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.NewsDetailActivity;
import com.sywb.chuangyebao.view.QAndADetailActivity;
import com.sywb.chuangyebao.view.TopicActivity;
import com.sywb.chuangyebao.view.VideoDetailActivity;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.adapter.BaseRecyclerMultiItemAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.utils.TimeUtils;
import org.bining.footstone.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public interface SearchResultContract {

    interface View extends BaseRecyclerContract.View {
    }

    class Presenter extends BaseRecyclerContract.Presenter<View> {

        private SearchAdapter recyclerAdapter;

        private String keyword;
        private String itemType;
        private int pageNumber = 1;

        @Override
        public void onStart() {
            super.onStart();
            recyclerAdapter = new SearchAdapter(mActivity, mView);
            setRecyclerAdapter(recyclerAdapter);
        }

        public void initData(String keyword, String itemType) {
            this.keyword = keyword;
            this.itemType = itemType;
            if (recyclerAdapter != null) {
                recyclerAdapter.setKeyword(keyword);
                initData();
            }
        }

        @Override
        public void initData() {
            super.initData();
            pageNumber = 1;
            getSearchList();
        }

        @Override
        public void onStartLoadMore() {
            pageNumber++;
            getSearchList();
        }

        private void getSearchList() {
            HttpUtils.getContentList(itemType, null, keyword, pageNumber, null, null, null, new HttpCallback<List<SuperInfo>>() {

                @Override
                public void onSuccess(List<SuperInfo> superInfos) {
                    for (SuperInfo superInfo : superInfos) {
                        superInfo.setItemType(superInfo.item_style);
                    }
                    if (pageNumber == 1) {
                        recyclerAdapter.clearDatas();
                    }
                    recyclerAdapter.notifyDataChangedAfterLoadMore(superInfos);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    onEndLoadMore();
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                    isNoData();
                }
            });
        }

        @Override
        public void onRecyclerItemClick(int i) {
            SuperInfo superInfo = recyclerAdapter.getItem(i);
            switch (superInfo.item_style) {
                case Constants.NEWS_TEXT:
                case Constants.NEWS_RIGHT_PIC_VIDEO:
                case Constants.NEWS_CENTER_SINGLE_PIC:
                case Constants.NEWS_THREE_PICS:
                    NewsInfo newsInfo = JSON.parseObject(superInfo.content, NewsInfo.class);
                    newsInfo.hits += 1;
                    newsInfo.count.hits += 1;
                    superInfo.content = JSON.toJSONString(newsInfo);
                    recyclerAdapter.notifyDataSetChanged();
                    mView.advance(NewsDetailActivity.class, newsInfo.item_id);
                    break;
                case Constants.QANDA_TEXT:
                case Constants.QANDA_PIC_ONE:
                case Constants.QANDA_PIC_THREE:
                case Constants.QANDA_MEDIA:
                    QuestionInfo question = JSON.parseObject(superInfo.content, QuestionInfo.class);
                    mView.advance(QAndADetailActivity.class, question.item_id);
                    break;
                case Constants.VIDEO_LIST:
                    VideoData videoInfo = JSON.parseObject(superInfo.content, VideoData.class);
                    mView.advance(VideoDetailActivity.class, videoInfo.item_id);
                    break;
                case Constants.USER_LIST:
                    SearchUser user = JSON.parseObject(superInfo.content, SearchUser.class);
                    Utils.goUserIndex(mView, user.uid);
//                    mView.advance(UserIndexActivity.class, user.uid);
                    break;
            }
        }

        @Override
        public void onRecyclerItemChildClick(android.view.View view, int i) {
            if (view.getId() == R.id.tv_follow) {
                SearchUser user = JSON.parseObject(recyclerAdapter.getItem(i).content, SearchUser.class);
                follow(user.uid, !user.is_follow, i);
            }
        }

        /**
         * 关注/取消关注
         *
         * @param targetId 被关注对象id
         * @param isFollow 关注or取消关注（1：关注 ，0：取消）
         */
        public void follow(int targetId, boolean isFollow, int postion) {
            if (!Utils.checkIsLogin()) {
                return;
            }
            HttpUtils.follow(targetId, Constants.TOPIC_TYPE_USER, isFollow, new HttpCallback<Object>(postion) {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Object o) {
                    int postion = (int) data;
                    SuperInfo superInfo = recyclerAdapter.getItem(postion);
                    SearchUser user = JSON.parseObject(superInfo.content, SearchUser.class);
                    ToastUtils.show(mContext, user.is_follow ? "取消关注" : "关注成功");
                    user.is_follow = !user.is_follow;
                    superInfo.content = JSON.toJSONString(user);
                    recyclerAdapter.notifyDataSetChanged();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }
    }

    class SearchAdapter extends BaseRecyclerMultiItemAdapter<SuperInfo> {

        private Activity mActivity;
        private View mView;

        private String keyword;

        public SearchAdapter(Activity activity, View view) {
            super(activity, null);
            this.mActivity = activity;
            this.mView = view;
            addItemType(Constants.NEWS_TEXT, R.layout.item_news_text);//文章纯文字布局
            addItemType(Constants.NEWS_RIGHT_PIC_VIDEO, R.layout.item_news_right_pic);//文章右侧小图布局
            addItemType(Constants.NEWS_CENTER_SINGLE_PIC, R.layout.item_news_center_pic);//文章居中大图布局
            addItemType(Constants.NEWS_THREE_PICS, R.layout.item_news_three_pics);//文章三张图片布局
            addItemType(Constants.QANDA_TEXT, R.layout.item_search_qanda);//问答布局
            addItemType(Constants.QANDA_PIC_ONE, R.layout.item_search_qanda);//问答布局
            addItemType(Constants.QANDA_PIC_THREE, R.layout.item_search_qanda);//问答布局
            addItemType(Constants.QANDA_MEDIA, R.layout.item_search_qanda);//问答布局
            addItemType(Constants.VIDEO_LIST, R.layout.item_video_right_pic);//视频布局
            addItemType(Constants.USER_LIST, R.layout.item_search_user);//用户布局
        }

        public void setKeyword(String keyword) {
            this.keyword = keyword;
        }

        @Override
        protected int getDefItemViewType(int position) {
            if (position >= getDataCount()) {
                return 0x00000333;
            }
            return super.getDefItemViewType(position);
        }

        @Override
        protected void setMultiData(ViewHolderHelper viewHolderHelper, int i, SuperInfo superInfo) {
            if (superInfo.item_style >= Constants.NEWS_TEXT && superInfo.item_style <= Constants.NEWS_THREE_PICS) {
                NewsInfo newsInfo = JSON.parseObject(superInfo.content, NewsInfo.class);

                if (TextUtils.isEmpty(newsInfo.title)) {
                    return;
                }

                if (TextUtils.isEmpty(keyword) || !newsInfo.title.contains(keyword)) {
                    viewHolderHelper.setText(R.id.tv_title, newsInfo.title);
                } else {
                    TextView title = viewHolderHelper.getView(R.id.tv_title);

                    List<Integer> indexs = new ArrayList<>();

                    int index = newsInfo.title.indexOf(keyword);

                    while (index >= 0) {
                        indexs.add(index);
                        index = index + keyword.length();
                        index = newsInfo.title.indexOf(keyword, index);
                    }

                    SpannableStringBuilder builder = new SpannableStringBuilder(newsInfo.title);

                    for (int ind : indexs) {
                        ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.colorTheme));
                        builder.setSpan(colorSpan, ind, ind + keyword.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }

                    title.setText(builder);
                }

                if (newsInfo.owner != null) {
                    viewHolderHelper.setText(R.id.tv_author, newsInfo.owner.getShowName());
                } else {
                    viewHolderHelper.setText(R.id.tv_author, newsInfo.writer);
                }

                viewHolderHelper.setText(R.id.tv_time, TimeUtils.transformDate10(newsInfo.publish_time));

                viewHolderHelper.setVisibility(R.id.tv_tag, android.view.View.GONE);

                // if (TextUtils.isEmpty(newsInfo.source)) {
                // viewHolderHelper.setVisibility(R.categoryId.tv_tag, View.GONE);
                // } else {
                // viewHolderHelper
                // .setVisibility(R.categoryId.tv_tag, View.VISIBLE)
                // .setText(R.categoryId.tv_tag, newsInfo.source);
                // }

                viewHolderHelper.setText(R.id.tv_comment_num, newsInfo.count.getHitsString());

                switch (superInfo.getItemType()) {
                    case Constants.NEWS_THREE_PICS:
                        RatioImageView iv_img1 = viewHolderHelper.getView(R.id.iv_img1);
                        RatioImageView iv_img2 = viewHolderHelper.getView(R.id.iv_img2);
                        RatioImageView iv_img3 = viewHolderHelper.getView(R.id.iv_img3);

                        iv_img1.setVisibility(android.view.View.INVISIBLE);
                        iv_img2.setVisibility(android.view.View.INVISIBLE);
                        iv_img3.setVisibility(android.view.View.INVISIBLE);

                        if (newsInfo.thumbnails != null && newsInfo.thumbnails.size() > 0) {
                            for (int j = 0; j < newsInfo.thumbnails.size(); j++) {
                                String thumbnail = newsInfo.thumbnails.get(j).trim();
                                if (!TextUtils.isEmpty(thumbnail)) {
                                    switch (j) {
                                        case 0:
                                            iv_img1.setVisibility(android.view.View.VISIBLE);
                                            GlideUtils.getNormalIamgeToUrl(mActivity, thumbnail, iv_img1, R.drawable.news_pic_default);
                                            break;
                                        case 1:
                                            iv_img2.setVisibility(android.view.View.VISIBLE);
                                            GlideUtils.getNormalIamgeToUrl(mActivity, thumbnail, iv_img2, R.drawable.news_pic_default);
                                            break;
                                        case 2:
                                            iv_img3.setVisibility(android.view.View.VISIBLE);
                                            GlideUtils.getNormalIamgeToUrl(mActivity, thumbnail, iv_img3, R.drawable.news_pic_default);
                                            break;
                                    }
                                }
                            }
                        }
                        break;
                    case Constants.NEWS_RIGHT_PIC_VIDEO:
                        RatioImageView iv_img_right = viewHolderHelper.getView(R.id.iv_img);
                        iv_img_right.setImageResource(R.drawable.news_pic_default);
                        if (newsInfo.thumbnails != null && newsInfo.thumbnails.size() > 0 && !TextUtils.isEmpty(newsInfo.thumbnails.get(0).trim())) {
                            GlideUtils.getNormalIamgeToUrl(mActivity, newsInfo.thumbnails.get(0), iv_img_right, R.drawable.news_pic_default);
                        }
                        viewHolderHelper.setVisibility(R.id.tv_duration, android.view.View.GONE);
                        break;
                    case Constants.NEWS_CENTER_SINGLE_PIC:
                        RatioImageView iv_img_center = viewHolderHelper.getView(R.id.iv_img);
                        iv_img_center.setImageResource(R.drawable.news_pic_default);
                        if (newsInfo.thumbnails != null && newsInfo.thumbnails.size() > 0 && !TextUtils.isEmpty(newsInfo.thumbnails.get(0).trim())) {
                            GlideUtils.getNormalIamgeToUrl(mActivity, newsInfo.thumbnails.get(0), iv_img_center, R.drawable.news_pic_default);
                        }
                        viewHolderHelper.setVisibility(R.id.tv_duration, android.view.View.GONE);
                        break;
                }
            } else if (superInfo.item_style >= Constants.QANDA_TEXT && superInfo.item_style <= Constants.QANDA_MEDIA) {

                QuestionInfo model = JSON.parseObject(superInfo.content, QuestionInfo.class);
                model.setTopic();

                //设置富文本
                RichTextView richTextView = viewHolderHelper.getView(R.id.rtv_title);
                richTextView.setDataPostion(i);
                richTextView.setSearch(true);
                richTextView.setKeyword(keyword);
                richTextView.setRichText(model.title, model.richInfoList);
                richTextView.setOnLinkClickListener(new RichTextView.OnLinkClickListener() {
                    @Override
                    public void onAtClick(RichTextView richTextView, Object userId) {
//                        mView.advance(UserIndexActivity.class, userId);
                        Utils.goUserIndex(mView, (Integer) userId);
                    }

                    @Override
                    public void onTopicClick(RichTextView richTextView, Object topicId) {
                        mView.advance(TopicActivity.class, topicId);
                    }

                    @Override
                    public void onEmojiClick(RichTextView richTextView, Object emoji) {
                    }

                    @Override
                    public void onUrlClick(RichTextView richTextView, Object url) {
                    }

                    @Override
                    public void onAllClick(RichTextView richTextView) {
                        SuperInfo superInfo = getItem(richTextView.getDataPostion());
                        QuestionInfo model = JSON.parseObject(superInfo.content, QuestionInfo.class);
                        mView.advance(QAndADetailActivity.class, model.item_id);
                    }
                });

                if (!TextUtils.isEmpty(model.answer)) {
                    viewHolderHelper.setText(R.id.tv_answer, model.answer);
                    viewHolderHelper.setVisibility(R.id.tv_answer, true);
                } else {
                    viewHolderHelper.setVisibility(R.id.tv_answer, false);
                }

                viewHolderHelper.setText(R.id.tv_answer_num, model.count.getAnswer());
            } else if (superInfo.item_style == Constants.VIDEO_LIST) {
                VideoData videoInfo = JSON.parseObject(superInfo.content, VideoData.class);

                ImageView ivImg = viewHolderHelper.getView(R.id.iv_img);
                GlideUtils.getNormalIamgeToUrl(mActivity, videoInfo.logo, ivImg);

                if (TextUtils.isEmpty(keyword) || !videoInfo.title.contains(keyword)) {
                    viewHolderHelper.setText(R.id.tv_title, videoInfo.title);
                } else {
                    TextView title = viewHolderHelper.getView(R.id.tv_title);

                    List<Integer> indexs = new ArrayList<>();

                    int index = videoInfo.title.indexOf(keyword);

                    while (index >= 0) {
                        indexs.add(index);
                        index = index + keyword.length();
                        index = videoInfo.title.indexOf(keyword, index);
                    }

                    SpannableStringBuilder builder = new SpannableStringBuilder(videoInfo.title);

                    for (int ind : indexs) {
                        ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.colorTheme));
                        builder.setSpan(colorSpan, ind, ind + keyword.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }

                    title.setText(builder);
                }

                viewHolderHelper.setText(R.id.tv_duration, DateTimeUtils.secToTime(videoInfo.length));
                viewHolderHelper.setVisibility(R.id.tv_tag, false);
                viewHolderHelper.setText(R.id.tv_author, videoInfo.owner.getShowName());
                viewHolderHelper.setText(R.id.tv_comment_num, videoInfo.count.getPlayTimesTotal());
                viewHolderHelper.setText(R.id.tv_time, TimeUtils.transformDate10(videoInfo.publish_time));
            } else {
                SearchUser searchUser = JSON.parseObject(superInfo.content, SearchUser.class);

                NewsOwner newsOwner = searchUser.owner;

                ImageView imageView = viewHolderHelper.getView(R.id.iv_face);
                GlideUtils.getCircleImageToUrl(mActivity, newsOwner.getShowAvatar(), imageView, R.drawable.head_image);

                // viewHolderHelper.setText(R.id.tv_user_name, newsOwner.getShowName());

                if (TextUtils.isEmpty(keyword) || !newsOwner.getShowName().contains(keyword)) {
                    viewHolderHelper.setText(R.id.tv_user_name, newsOwner.getShowName());
                } else {
                    TextView title = viewHolderHelper.getView(R.id.tv_user_name);

                    List<Integer> indexs = new ArrayList<>();

                    int index = newsOwner.getShowName().indexOf(keyword);

                    while (index >= 0) {
                        indexs.add(index);
                        index = index + keyword.length();
                        index = newsOwner.getShowName().indexOf(keyword, index);
                    }

                    SpannableStringBuilder builder = new SpannableStringBuilder(newsOwner.getShowName());

                    for (int ind : indexs) {
                        ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.colorTheme));
                        builder.setSpan(colorSpan, ind, ind + keyword.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }

                    title.setText(builder);
                }

                ImageView ivLabel = viewHolderHelper.getView(R.id.iv_label);
                TextView tvUserType = viewHolderHelper.getView(R.id.tv_user_type);

                int userRole = newsOwner.getUserRole();
                if (userRole == Constants.USER_TYPE_NORMAL) {
                    ivLabel.setVisibility(android.view.View.GONE);
                    tvUserType.setVisibility(android.view.View.GONE);
                } else {
                    ivLabel.setVisibility(android.view.View.VISIBLE);
                    tvUserType.setVisibility(android.view.View.VISIBLE);
                    switch (userRole) {
                        case Constants.USER_TYPE_V:
                            ivLabel.setImageResource(R.drawable.official_icon);
                            tvUserType.setText("官方号");
                            break;
                        case Constants.USER_TYPE_PROJECT:
                            ivLabel.setImageResource(R.drawable.icon_project);
                            tvUserType.setText("项目号");
                            break;
                        case Constants.USER_TYPE_SERVICE:
                            ivLabel.setImageResource(R.drawable.icon_service);
                            tvUserType.setText("服务号");
                            break;
                        case Constants.USER_TYPE_TUTOR:
                            ivLabel.setImageResource(R.drawable.icon_teacher);
                            tvUserType.setText("导师");
                            break;
                    }
                }

                viewHolderHelper.setText(R.id.tv_info, newsOwner.brief_intro);
                viewHolderHelper.setText(R.id.tv_other, newsOwner.fans_num + "粉丝");

                TextView tvFollow = viewHolderHelper.getView(R.id.tv_follow);
                if (searchUser.is_follow) {
                    tvFollow.setText("已关注");
                    tvFollow.setTextColor(ContextCompat.getColor(mContext, R.color.colorGray));
                    tvFollow.setBackgroundResource(R.drawable.round_line_gray);
                } else {
                    tvFollow.setText("+ 关注");
                    tvFollow.setTextColor(ContextCompat.getColor(mContext, R.color.colorLight));
                    tvFollow.setBackgroundResource(R.drawable.round_pie_theme);
                }
                viewHolderHelper.setItemChildClickListener(R.id.tv_follow);
            }
        }
    }
}

